(function() {
    angular.module('app').directive('echartsDrawCanvasLine', ['$rootScope', '$timeout', function($rootScope, $timeout) {
        return {
            restrict: 'A',
            scope: {
                echartsLink: '&'
            },
            link: function(scope, iElement, iAttrs) {

                // $(iElement).height($(iElement).width());

                scope.chart = echarts.init(iElement[0]);


                //图
                var clearFunc = $rootScope.$on('echart_draw_line_EV', function(e, data, id) {
                    console.log('echart_draw_line_EV js ');

                    console.log(data);

                    if (iAttrs.id == id) { //防止覆盖
                        // console.log('id匹配');
                        draw(data);
                    }
                    
                });
                //loading
                var clear = $rootScope.$on('echart_draw_line_loading_EV', function(e, id) {
                    // console.log('echart_draw_line_loading_EV js ');

                    if (iAttrs.id == id) { //防止覆盖
                        // console.log('id匹配 loading');
                        loading();
                    }
                });


                function draw(data) {
                    scope.chart.clear();
                    scope.chart.resize();
                    data = chartPieResize(data);
                    scope.chart.setOption(data);
                    scope.chart.hideLoading();

                    if(typeof scope.echartsLink == 'function'){
                        scope.chart.on('click', scope.echartsLink());
                    }

                }

                function loading() {
                    scope.chart.clear();
                    scope.chart.showLoading();
                }

                function chartPieResize(data) {
                    if (data.series[0].type == 'pie') {
                        var width = $(iElement).width();
                        var height = $(iElement).height();
                        // console.log((width / height).toFixed(2));
                        if ((width / height).toFixed(2) > 1.0) {
                            data.series[0].radius = '45%';
                        }

                    }
                    // console.log(data);
                    return data;

                }

                scope.$on('$destroy', function() {
                    clearFunc();
                    clear();
                });
            }
        };
    }]);
})();
